package com.ctcemti.mdm.project.sys.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.ctcemti.mdm.common.util.BatchOperationUtils;
import com.ctcemti.mdm.common.util.ExcelExportStylerImpl;
import com.ctcemti.mdm.common.util.ExcelParseUtils;
import com.ctcemti.mdm.project.common.excelverifyhandler.ExcelVerifyHandlerForRole;
import com.ctcemti.mdm.project.sys.dao.*;
import com.ctcemti.mdm.project.sys.entity.OrgJob;
import com.ctcemti.mdm.project.sys.entity.OrgRole;
import com.ctcemti.mdm.project.sys.entity.RelPersonRole;
import com.ctcemti.mdm.project.sys.entity.RelRoleJob;
import com.ctcemti.mdm.project.sys.service.IOrgRoleService;
import com.ctcemti.mdm.project.common.excelverifyhandler.ExcelVerifyHandlerForRole;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;

@Service
@Slf4j
public class OrgRoleServiceImpl implements IOrgRoleService {

    @Autowired
    private OrgRoleMapper orgRoleMapper;
    @Autowired
    private RelDisciplinesMethodsMapper relDisciplinesMethodsMapper;
    @Autowired
    private InfDictItemMapper infDictItemMapper;
    @Autowired
    private RelPersonRoleMapper relPersonRoleMapper;
    @Autowired
    private RelRoleJobMapper relRoleJobMapper;
    @Value("${ctcemti.errorfilepath}")
    private String errorfilepath;


    @Transactional
    @Override
    public int deleteByPrimaryKey(Integer id) {
        return orgRoleMapper.deleteByPrimaryKey(id);
    }

    @Transactional
    @Override
    public int insert(OrgRole record) {
        return orgRoleMapper.insert(record);
    }

    @Override
    public OrgRole selectByPrimaryKey(String id) {
        return orgRoleMapper.selectByPrimaryKey(id);
    }

    @Transactional
    @Override
    public int updateByPrimaryKey(OrgRole record) {
        return orgRoleMapper.updateByPrimaryKey(record);
    }

    @Override
    public List<OrgRole> selectAllOrgRole(OrgRole record) {
        Example example = new Example(OrgRole.class);
        Example.Criteria criteria = example.createCriteria();
        if(!StringUtil.isEmpty(record.getName())){
            criteria.andLike("name",'%'+record.getName()+'%');
        }
        if(record.getOrgType()!=null){
            criteria.andLike("orgType",'%'+record.getOrgType()+"%");
        }
        return orgRoleMapper.selectByExample(example);
    }

    @Override
    public int insertSelective(OrgRole record) {
        return orgRoleMapper.insertSelective(record);
    }

    @Override
    public OrgRole selectByPrimaryKey(Integer id) {
        return orgRoleMapper.selectByPrimaryKey(id);
    }


    @Override
    public List<OrgRole> selectOrgRole(OrgRole OrgRole) {
        return orgRoleMapper.select(OrgRole);
    }

    @Override
    public PageInfo selectAllOrgRoleByPage(OrgRole record) {
        PageHelper.startPage(record.getPageIndex(),record.getPageSize(),"oro.sort");
        List<OrgRole> list =  orgRoleMapper.selectListByCondition(record);
        PageInfo<OrgRole> pageInfo =  new PageInfo<OrgRole>(list);
        return pageInfo;
    }

    @Transactional
    @Override
    public Map<String, Object> uploadFile(MultipartFile multipartFile, HttpServletResponse response) throws SQLException, IOException {
        Map<String,Object> resultMap = new HashMap<String,Object>();
        ExcelImportResult<OrgRole> excelImportResult = ExcelParseUtils.importExcelMore(multipartFile,0,1,OrgRole.class,new ExcelVerifyHandlerForRole(orgRoleMapper,infDictItemMapper));
        boolean flag = true;
        if(excelImportResult == null){
            resultMap.put("flag",flag);
        }else if(excelImportResult.getFailList().size()>0){//验证失败，重新写入excel，并保存
            String filename = UUID.randomUUID().toString();//获取新的文件名
            File folder = new File(errorfilepath);//文件夹
            if(!folder.exists()){
                boolean mkFlag = folder.mkdirs();
                if (mkFlag) {
                    log.error("未找到上传文件夹，新建文件夹");
                }
            }
            FileOutputStream fos = null;
            try {
                //fileOutputStream = new FileOutputStream(file);
                //excelImportResult.getWorkbook().write(fileOutputStream);
                List<OrgRole> slist = excelImportResult.getList();//获取所有成功项
                List<OrgRole> flist = excelImportResult.getFailList();//获取所有失败项
                slist.addAll(flist);
                Collections.sort(slist);
                ExportParams exportParams = new ExportParams(null,null,"错误列表");
                exportParams.setStyle(ExcelExportStylerImpl.class);
                Workbook workbook = ExcelExportUtil.exportExcel(exportParams,OrgRole.class, slist);
                fos = new FileOutputStream(errorfilepath+"/"+filename+".xls");
                workbook.write(fos);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if(fos!=null){
                    fos.close();
                }
            }
            flag = false;
            resultMap.put("flag",flag);
            resultMap.put("filecode",filename);
        }else{//成功验证，准备导入数据
            List<OrgRole> list = excelImportResult.getList();
            List<String> codelist = new ArrayList<String>();//归集编号查询id
            //角色插入
            BatchOperationUtils<OrgRole> batchOperationUtils = new BatchOperationUtils();
            batchOperationUtils.batchOperation(list, 200,var->orgRoleMapper.insertBatch(var));
            resultMap.put("flag",flag);
        }
        return resultMap;
    }

    @Override
    @Transactional
    public int deleteByPrimaryKeys(String ids) {
        log.info("删除角色"+ids+"成功");
        return orgRoleMapper.deleteByPrimaryKeys(Arrays.asList(ids.split(",")));
    }

    @Override
    public int bindRoleAndPerson(String roleid, String personids) {
        String personid[] = personids.split(",");
        List<RelPersonRole> list = new ArrayList<RelPersonRole>();
        for(int i=0;i<personid.length;i++){
            RelPersonRole RelPersonRole = new RelPersonRole();
            RelPersonRole.setPersonId(personid[i]);
            RelPersonRole.setRoleId(roleid);
            list.add(RelPersonRole);
        }
        return relPersonRoleMapper.insertBatch(list);
    }
    @Override
    public int unbindRoleAndPerson(String roleid, String personids) {
        String personid[] = personids.split(",");
        List<RelPersonRole> list = new ArrayList<RelPersonRole>();
        for(int i=0;i<personid.length;i++){
            //删除原绑定关系
            Example example = new Example(RelPersonRole.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("roleId",roleid);
            criteria.andEqualTo("personId",personid[i]);
            relPersonRoleMapper.deleteByExample(example);
        }
        return 1;
    }

    @Override
    @Transactional
    public int bindRoleAndJob(String roleid, String jobids) {
        List<RelRoleJob> list = new ArrayList<RelRoleJob>();
        //删除原绑定关系
        Example example = new Example(RelRoleJob.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("roleId",roleid);
        if(!StringUtil.isEmpty(jobids)){
            String[] jobid = jobids.split(",");
            for(int i=0;i<jobid.length;i++){
                RelRoleJob relRoleJob = new RelRoleJob();
                relRoleJob.setRoleId(roleid);
                relRoleJob.setJobId(jobid[i]);
                list.add(relRoleJob);
            }
            //删除原绑定关系
            relRoleJobMapper.deleteByExample(example);
            //重新挂接方法
            return relRoleJobMapper.insertBatch(list);
        }else{
            return relRoleJobMapper.deleteByExample(example);
        }
    }


    @Override
    public PageInfo<OrgJob> selectAllOrgJobByPage(OrgJob entity,String roleId) {
        PageHelper.startPage(entity.getPageIndex(),entity.getPageSize(),"id");
        Map<String,Object> param = new HashMap<>();
        if(entity!=null){
            if(!StringUtil.isEmpty(entity.getJob())){
                param.put("job",entity.getJob());
            }
            if(!StringUtil.isEmpty(entity.getName())){
                param.put("name",entity.getName());
            }
        }

        if(!StringUtil.isEmpty(roleId)){
            param.put("roleId",roleId);
        }
        List<OrgJob> list = orgRoleMapper.selectJobByCondition(param);

        return new PageInfo<OrgJob>(list);
    }

}
